package cn.lopr.im.api.service.impl;

import cn.lopr.im.api.service.ICosService;
import cn.lopr.im.api.utils.cos.CosClient;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author shuangyang7
 * @date 2021/5/19 22:15
 */
@Service
public class CosServiceImpl implements ICosService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private CosClient cosClient;

    @Override
    public JSONObject getTempSecret() {
        String key = redisTemplate.opsForValue().get("cos-temp-secret");
        if (!StringUtils.isEmpty(key)) {
            return new JSONObject(key);
        }

        JSONObject tempSecret = cosClient.getTempSecret();
        tempSecret.put("bucket", cosClient.getBucket());
        tempSecret.put("region", cosClient.getRegion());
        redisTemplate.opsForValue().set("cos-temp-secret", tempSecret.toString(), cosClient.getDurationSeconds() - 180, TimeUnit.SECONDS);

        return tempSecret;
    }
}
